﻿<script lang="ts" name="sysstocktakingorder" setup>
import { ref, reactive, onMounted, computed, watch } from "vue";
import { ElMessage } from "element-plus";
import type { FormRules } from "element-plus";
import { useSysstocktakingorderApi } from '/@/api/OutWarehou/sysstocktakingorder';
import { useGoodsModelApi } from '/@/api/Goods/Details/goodsModel';
import { useWarehouseModelApi } from '/@/api/interacting/warehouse/warehouseModel';

//父级传递来的函数，用于回调
const emit = defineEmits(["reloadTable"]);
const sysstocktakingorderApi = useSysstocktakingorderApi();
const goodsModelApi = useGoodsModelApi();
const warehouseModelApi = useWarehouseModelApi();
const ruleFormRef = ref();

const state = reactive({
	title: '',
	loading: false,
	showDialog: false,
	ruleForm: {} as any,
	stores: {},
	dropdownData: {} as any,
	inventoryResultOptions: [
		{ label: '草稿', value: '草稿' },
		{ label: '有盘盈', value: '有盘盈' },
		{ label: '有盘亏', value: '有盘亏' }
	],
	stockTakingTypeOptions: [
		{ label: '存货盘点', value: '存货盘点' },
		{ label: '期初盘点', value: '期初盘点' },
		{ label: '期末盘点', value: '期末盘点' }
	],
	goodsList: [] as any[],
	warehouseList: [] as any[]
});

// 验证盘盈盘亏不能同时存在
const validateProfitLoss = (_rule: any, _value: any, callback: any) => {
  const form = state.ruleForm;
  const hasProfitData = (form.profitQuantity && form.profitQuantity > 0) || (form.profitAmount && form.profitAmount > 0);
  const hasLossData = (form.lossQuantity && form.lossQuantity > 0) || (form.lossAmount && form.lossAmount > 0);
  
  if (hasProfitData && hasLossData) {
    callback(new Error('盘盈数量与金额和盘亏数量与金额不能同时存在'));
  } else {
    callback();
  }
};

// 验证盘盈数量不能超过盘点数量
const validateProfitQuantity = (_rule: any, value: any, callback: any) => {
  const quantity = state.ruleForm.quantity || 0;
  if (value && value > quantity) {
    callback(new Error('盘盈数量不能超过盘点数量'));
  } else {
    callback();
  }
};

// 验证盘亏数量不能超过盘点数量
const validateLossQuantity = (_rule: any, value: any, callback: any) => {
  const quantity = state.ruleForm.quantity || 0;
  if (value && value > quantity) {
    callback(new Error('盘亏数量不能超过盘点数量'));
  } else {
    callback();
  }
};

// 自行添加其他规则
const rules = ref<FormRules>({
  code: [{required: true, message: '请选择盘点单号！', trigger: 'blur',},],
  outStatus: [{required: true, message: '请选择出库状态！', trigger: 'change',},],
  inStatus: [{required: true, message: '请选择入库状态！', trigger: 'change',},],
  documentStatus: [{required: true, message: '请选择单据状态！', trigger: 'change',},],
  profitQuantity: [
    { validator: validateProfitQuantity, trigger: 'change' },
    { validator: validateProfitLoss, trigger: 'change' }
  ],
  lossQuantity: [
    { validator: validateLossQuantity, trigger: 'change' },
    { validator: validateProfitLoss, trigger: 'change' }
  ],
  profitAmount: [{ validator: validateProfitLoss, trigger: 'change' }],
  lossAmount: [{ validator: validateProfitLoss, trigger: 'change' }],
});

// 加载货品列表
const loadGoodsList = async () => {
	try {
		const res = await goodsModelApi.page({ pageSize: 1000, pageNo: 1 });
		if (res.data.result && res.data.result.items) {
			state.goodsList = res.data.result.items;
		}
	} catch (error) {
		console.error('加载货品列表失败:', error);
	}
};

// 加载仓库列表
const loadWarehouseList = async () => {
	try {
		const res = await warehouseModelApi.page({ pageSize: 1000, pageNo: 1 });
		if (res.data.result && res.data.result.items) {
			state.warehouseList = res.data.result.items;
		}
	} catch (error) {
		console.error('加载仓库列表失败:', error);
	}
};

// 货品选择变化时，自动设置对应的仓库
const handleGoodsChange = (goodsCode: string) => {
	if (goodsCode) {
		const selectedGoods = state.goodsList.find(item => item.goodsCode === goodsCode);
		if (selectedGoods && selectedGoods.goodsWareId) {
			// 根据货品的仓库ID查找仓库，存储仓库ID或编码（根据实际数据库设计）
			const warehouse = state.warehouseList.find(w => w.id === selectedGoods.goodsWareId);
			if (warehouse) {
				// 如果数据库中存储的是ID，则使用ID；如果是编码，则使用编码
				// 根据现有数据判断，如果warehouseName是长数字，说明存的是ID
				state.ruleForm.warehouseName = warehouse.wareCode || warehouse.id?.toString() || '';
			}
		}
	}
};

// 计算盘盈字段是否禁用
const isProfitDisabled = computed(() => {
	const result = state.ruleForm.inventoryResult;
	return result === '草稿' || result === '有盘亏';
});

// 计算盘亏字段是否禁用
const isLossDisabled = computed(() => {
	const result = state.ruleForm.inventoryResult;
	return result === '草稿' || result === '有盘盈';
});

// 监听盘点结果变化，自动清空不允许的字段
watch(() => state.ruleForm.inventoryResult, (newValue) => {
	if (newValue === '草稿') {
		// 草稿状态，清空所有盘盈盘亏数据
		state.ruleForm.profitQuantity = null;
		state.ruleForm.profitAmount = null;
		state.ruleForm.lossQuantity = null;
		state.ruleForm.lossAmount = null;
	} else if (newValue === '有盘盈') {
		// 有盘盈状态，清空盘亏数据
		state.ruleForm.lossQuantity = null;
		state.ruleForm.lossAmount = null;
	} else if (newValue === '有盘亏') {
		// 有盘亏状态，清空盘盈数据
		state.ruleForm.profitQuantity = null;
		state.ruleForm.profitAmount = null;
	}
});

// 页面加载时
onMounted(async () => {
	await loadGoodsList();
	await loadWarehouseList();
});

// 打开弹窗
const openDialog = async (row: any, title: string) => {
	state.title = title;
	row = row ?? {  };
	state.ruleForm = row.id ? await sysstocktakingorderApi.detail(row.id).then(res => res.data.result) : JSON.parse(JSON.stringify(row));
	// 如果是新增，设置盘点结果默认值为"草稿"
	if (!state.ruleForm.id && !state.ruleForm.inventoryResult) {
		state.ruleForm.inventoryResult = '草稿';
	}
	state.showDialog = true;
};

// 关闭弹窗
const closeDialog = () => {
	emit("reloadTable");
	state.showDialog = false;
};

// 自动生成编号
const generateCode = () => {
	const now = new Date();
	const seconds = now.getSeconds().toString().padStart(2, '0'); // 秒数，两位数
	const milliseconds = now.getMilliseconds().toString().padStart(3, '0').substring(0, 2); // 毫秒数，取前两位
	const code = `PDDH${seconds}${milliseconds}`;
	state.ruleForm.code = code;
};

// 提交
const submit = async () => {
	ruleFormRef.value.validate(async (isValid: boolean, fields?: any) => {
		if (isValid) {
			let values = state.ruleForm;
			await sysstocktakingorderApi[state.ruleForm.id ? 'update' : 'add'](values);
			closeDialog();
		} else {
			ElMessage({
				message: `表单有${Object.keys(fields).length}处验证失败，请修改后再提交`,
				type: "error",
			});
		}
	});
};

//将属性或者函数暴露给父组件
defineExpose({ openDialog });
</script>
<template>
	<div class="sysstocktakingorder-container">
		<el-dialog v-model="state.showDialog" :width="800" draggable :close-on-click-modal="false">
			<template #header>
				<div style="color: #fff">
					<span>{{ state.title }}</span>
				</div>
			</template>
			<el-form :model="state.ruleForm" ref="ruleFormRef" label-width="auto" :rules="rules">
				<el-row :gutter="35">
					<el-form-item v-show="false">
					<el-input v-model="state.ruleForm.id" />
				</el-form-item>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20" >
					<el-form-item label="盘点单号" prop="code">
						<div style="display: flex; gap: 8px;">
							<el-input v-model="state.ruleForm.code" placeholder="请输入盘点单号" maxlength="64" show-word-limit clearable style="flex: 1;" />
							<el-button type="primary" @click="generateCode">自动生成编号</el-button>
						</div>
					</el-form-item>
				</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20" >
					<el-form-item label="盘点结果" prop="inventoryResult">
						<el-select v-model="state.ruleForm.inventoryResult" placeholder="请选择盘点结果" clearable filterable>
							<el-option
								v-for="item in state.inventoryResultOptions"
								:key="item.value"
								:label="item.label"
								:value="item.value"
							/>
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20" >
				<el-form-item label="仓库名称" prop="warehouseName">
					<el-select v-model="state.ruleForm.warehouseName" placeholder="请选择仓库名称" clearable filterable disabled>
						<el-option
							v-for="item in state.warehouseList"
							:key="item.id"
							:label="item.wareName"
							:value="item.wareCode || item.id?.toString()"
						/>
					</el-select>
				</el-form-item>
			</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20" >
					<el-form-item label="盘点类型" prop="stockTakingType">
						<el-select v-model="state.ruleForm.stockTakingType" placeholder="请选择盘点类型" clearable filterable>
							<el-option
								v-for="item in state.stockTakingTypeOptions"
								:key="item.value"
								:label="item.label"
								:value="item.value"
							/>
						</el-select>
					</el-form-item>
				</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20" >
						<el-form-item label="盘点开始时间" prop="startTime">
							<el-date-picker v-model="state.ruleForm.startTime" type="date" placeholder="盘点开始时间" />
						</el-form-item>
					</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20" >
						<el-form-item label="盘点结束时间" prop="endTime">
							<el-date-picker v-model="state.ruleForm.endTime" type="date" placeholder="盘点结束时间" />
						</el-form-item>
					</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20" >
						<el-form-item label="出库状态" prop="outStatus">
							<g-sys-dict v-model="state.ruleForm.outStatus" code="DocumentStatusEnum" render-as="select" placeholder="请选择出库状态" clearable filterable />
						</el-form-item>
					</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20" >
						<el-form-item label="入库状态" prop="inStatus">
							<g-sys-dict v-model="state.ruleForm.inStatus" code="DocumentStatusEnum" render-as="select" placeholder="请选择入库状态" clearable filterable />
						</el-form-item>
					</el-col>
			<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20" >
			<el-form-item label="盘点货品" prop="goodsName">
				<el-select v-model="state.ruleForm.goodsName" placeholder="请选择盘点货品" clearable filterable @change="handleGoodsChange">
					<el-option
						v-for="item in state.goodsList"
						:key="item.goodsCode"
						:label="item.goodsName"
						:value="item.goodsCode"
					/>
				</el-select>
			</el-form-item>
		</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20" >
						<el-form-item label="盘点数量" prop="quantity">
							<el-input-number v-model="state.ruleForm.quantity" placeholder="请输入盘点数量" clearable />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20" >
						<el-form-item label="盘盈数量" prop="profitQuantity">
							<el-input-number v-model="state.ruleForm.profitQuantity" placeholder="请输入盘盈数量" clearable :min="0" :disabled="isProfitDisabled" />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20" >
						<el-form-item label="盘亏数量" prop="lossQuantity">
							<el-input-number v-model="state.ruleForm.lossQuantity" placeholder="请输入盘亏数量" clearable :min="0" :disabled="isLossDisabled" />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20" >
						<el-form-item label="盘盈金额" prop="profitAmount">
							<el-input-number v-model="state.ruleForm.profitAmount" placeholder="请输入盘盈金额" clearable :min="0" :precision="2" :disabled="isProfitDisabled" />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20" >
						<el-form-item label="盘亏金额" prop="lossAmount">
							<el-input-number v-model="state.ruleForm.lossAmount" placeholder="请输入盘亏金额" clearable :min="0" :precision="2" :disabled="isLossDisabled" />
						</el-form-item>
					</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20" >
						<el-form-item label="单据状态" prop="documentStatus">
							<g-sys-dict v-model="state.ruleForm.documentStatus" code="DocumentStatusEnum" render-as="select" placeholder="请选择单据状态" clearable filterable />
						</el-form-item>
					</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20" >
						<el-form-item label="备注" prop="remark">
							<el-input v-model="state.ruleForm.remark" placeholder="请输入备注" maxlength="512" show-word-limit clearable />
						</el-form-item>
					</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20" >
						<el-form-item label="软删除时间" prop="deleteTime">
							<el-date-picker v-model="state.ruleForm.deleteTime" type="date" placeholder="软删除时间" />
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="() => state.showDialog = false">取 消</el-button>
					<el-button @click="submit" type="primary" v-reclick="1000">确 定</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>
<style lang="scss" scoped>
:deep(.el-select), :deep(.el-input-number) {
  width: 100%;
}
</style>